package com.haiheng.voiceandbook.download

import android.util.Log
import com.haiheng.voiceandbook.Constants.Companion.ROOT_PATH
import com.it.bannner.MyApplication
import com.it.bannner.common.DownLoadFinishMsg
import com.it.bannner.common.Message
import com.it.bannner.log.LogWriter
import org.greenrobot.eventbus.EventBus
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.net.URL


/**
 * 下载管理
 */
class DownLoadManager {


    companion object {
        private val instance = DownLoadManager()
        fun getInstance(): DownLoadManager {
            return instance;
        }
    }


    /**
     * 开始下载任务
     */
    fun startDownLoadTask(list: List<String>) {
        //批量下载
        list.forEach {
            val runnable = DownLoadRunnable(it)
            //执行任务，最多执行核心线程数8，最大线程数8
            MyApplication.getInstance().executor.execute(runnable)
        }

    }

    /**
     * 下载任务
     */
    class DownLoadRunnable(val path: String) : Runnable {

        val TAG = "DownLoadRunnable"
        override fun run() {
            val array = path.split("/")
            val name = array[array.size - 1]
            val file = File(ROOT_PATH, name)
            downLoad(path, file, name)

        }

        /**
         * 下载
         */
        private fun downLoad(path: String, file: File, name: String) {
            try {

                LogWriter.e("当前线程${Thread.currentThread().name},正在下载${path}")
                val url = URL(path)
                val connection = url.openConnection()
                connection.connect()
                val contentLength: Int = connection.getContentLength()
                val input: InputStream = BufferedInputStream(url.openStream())

                if (file.exists()) {
                    //小于 说明下载不完整
                    if (file.length() < contentLength) {
                        //删掉文件
                        file.delete()
                        //写入文件
                        writeFileToDisk(input, name)
                    }
                } else {
                    writeFileToDisk(input, name)
                }

            } catch (e: Exception) {
                LogWriter.e("下载异常: ${e}")
            }


        }

        /**
         * 将文件 写入磁盘
         */
        fun writeFileToDisk(input: InputStream, name: String) {

            LogWriter.e("开始写入文件")
            val file = File(ROOT_PATH, name)
            if (!file.exists()) {
                file.createNewFile()
            }
            try {
                val fos = FileOutputStream(file)
                val bis = BufferedInputStream(input)
                val buffer = ByteArray(1024)
                var len: Int
                var total: Long = 0
                while ((bis.read(buffer).also { len = it } != -1)) {
                   // LogWriter.e("正在写入文件${len}")
                    fos.write(buffer, 0, len)
                    total += len
                }
                fos.flush()
                fos.close()
                bis.close()
                input.close()
                //下载完成通知其更新数据库
                val msg = Message()
                val downMsg = DownLoadFinishMsg()
                downMsg.name = name
                msg.downLoadFinishMsg = downMsg
                EventBus.getDefault().post(msg)


                LogWriter.e("写入文件完毕${Thread.currentThread().name},${path}")
            } catch (e: Exception) {
                file.delete()
                LogWriter.e("写入文件异常: ${e}")
            }
        }


    }
}